package com.okq.dao;

import com.okq.dao.base.Impl.BaseDao;
import com.okq.entity.Production;
import com.okq.util.page.Page;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Repository;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 描述 : 生产Dao
 * 作者 : zdl
 * 日期 : 2017/6/29 11:47
 */
@Repository
public class ProductionDao extends BaseDao {

    public void saveProduction(Production production) {
        super.save(production);
    }

    public void deleteProduction(Production production) {
        super.delete(production);
    }

    public void updateProduction(Production production) {
        super.update(production);
    }

    public void saveOrUpdateProduction(Production production) {
        super.saveOrUpdate(production);
    }

    public Production getProductionById(String id) {
        return (Production) super.get(Production.class, id);
    }

    public List<Production> listAllProduction() {
        String hql = "FROM Production WHERE isDelete = 0 ";
        return super.find(hql);
    }

    public Page<Production> pageByProduction(Page<Production> page, Production production) {
        StringBuilder hqlSb = new StringBuilder();
        hqlSb.append("FROM Production p WHERE p.isDelete = 0 ");
        if (production != null) {
            Map<String, Object> param = new HashMap<>();
            String batch = production.getBatch();
            if (StringUtils.isNotBlank(batch)) {
                hqlSb.append(" AND p.batch LIKE ?1 ");
                param.put("1", "%" + batch + "%");
            }
            Integer productType = production.getProductType();
            if (productType != null && productType != -1) {
                hqlSb.append(" AND p.productType = ?2 ");
                param.put("2", productType);
            }
            Integer state = production.getState();
            if (state != null && state != -1) {
                hqlSb.append(" AND p.state = ?3 ");
                param.put("3", state);
            }
            hqlSb.append(" ORDER BY p.createTime DESC ");
            return super.findByPage(page, hqlSb.toString(), param);
        }
        return page;
    }

    /**
     * 根据条件查询生产list
     *
     * @param batch 批次模糊查询字段
     * @return list
     */
    public List<Production> listProductionBybatch(String batch) {
        if (StringUtils.isNotBlank(batch)) {
            String hql = "FROM Production p WHERE p.isDelete = 0 AND p.batch LIKE '" + batch + "'";
            return super.find(hql);
        }
        return null;
    }

    /**
     * 查询最后一条生产信息
     *
     * @return production
     */
    public Production getLastProduction() {
        String hql = "FROM Production WHERE isDelete = 0 ORDER BY createTime DESC ";
        List<Production> pList = super.findMax(hql, 1);
        if (pList != null && pList.size() > 0) {
            return pList.get(0);
        } else {
            return null;
        }
    }

}
